using System;
using System.Text;
using System.Collections.Generic;
using Communication.Packets;
using ConnectServer;
using System.IO;
using Utilities.IO;
using Utilities.Conversion;

namespace ConnectServer.Protocol
{
    /// <summary>
    /// ServerList packet.
    /// </summary>
    public sealed class ServerListPacket : ConnectServerPacket
    {
        public new static int ID = 0x06;

        #region Ctor
        public ServerListPacket()
            : base(PacketType.C2, ID)
        {
            this.m_serverGroups = Config.Instance.Groups;
        }
        #endregion

        #region Serialization & Deserialization

        public ServerListPacket(BufferedStream buffer)
            : base(buffer)
        {
            // check if this is the right packet type.
            if (this.m_subId != ID)
            {
                throw new InvalidPacketIDError();
            }
        }

        public override void Serialize(BufferedStream buffer)
        {
            EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Big, buffer);
            writer.Write((short)this.getServerCount());
            int groupCount = 0;
            foreach (Config.ServerGroup group in this.m_serverGroups)
            {
                int serverCount = 0;
                foreach (Config.Server server in group.Servers)
                {
                    writer.Write((byte)serverCount);
                    writer.Write((byte)groupCount);
                    // Unknown. Need to understand this value.
                    writer.Write((short)90);
                    serverCount++;
                }
                groupCount++;
            }
            base.Serialize(buffer);
            buffer.Seek(0, SeekOrigin.Begin);
        }
        #endregion

        #region Privates
        private int getServerCount()
        {
            int count = 0;
            foreach (Config.ServerGroup group in this.m_serverGroups)
            {
                count += group.Servers.Count;
            }
            return count;
        }
        #endregion

        #region Fields
        private List<Config.ServerGroup> m_serverGroups;
        #endregion
    }
}
